import { login, getProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import getPageTitle from '@/utils/get-page-title'
// import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    UserInfo: {}
  },
  mutations: {
    // 格式
    // mutation名(state, 参数) {}
    setToken (state, newToken) {
      // 保存到vuex
      state.token = newToken
      // 保存到本地
      setToken(newToken)
    },
    reomveToken (state) {
      state.token = ''
      removeToken()
    },
    setUserInfo (state, newUserInfo) {
      state.UserInfo = newUserInfo
    },
    reomveUserInfo (state) {
      state.UserInfo = {}
    }
  },
  actions: {
    async getUserProfile (context) {
      // eslint-disable-next-line no-undef
      const res = await getProfile()

      // 获取原信息
      const info = await getUserDetailById(res.data.userId)
      console.log('getUserProfile.....', info.data)
      // 调用mutations
      context.commit('setUserInfo', { ...res.data, ...info.data })
    },
    async userLogin (context, userInfo) {
      try {
        console.log('userLogin', userInfo)
        const res = await login(userInfo)
        console.log(res)
        context.commit('setToken', res.data)
      } catch (err) {
        console.log(err)
        throw new Error(err)
      }
    },
    logout (context) {
      // 删除UserInfo
      context.commit('reomveUserInfo')
      // 删除token
      context.commit('reomveToken')
    }
  }
}

